import { login } from "@/api/index";
import { userStore } from "@/store/index";
import { router, showToast,cache } from "@/util/index";
Page({
  data: {
    isAgreed: false,
    isLoading: false,
    shouldShake: false,
  },
  /**
   * 切换同意协议的状态
   */
  toggleAgree() {
    if (this.data.isLoading) {
      return;
    }
    this.setData({
      isAgreed: !this.data.isAgreed,
    });
  },
  /**
   * 处理登录按钮点击事件
   */
  async handleLogin() {
    if (this.data.isLoading) return;
    if (!this.data.isAgreed) {
			this.shakePrivacyArea();
			showToast("请先阅读并同意协议",2000)
      return;
    }
    this.setData({ isLoading: true });
    try {
      wx.login({
        success: async ({ code }) => {
					const data = await login({ code });
					cache.set("uid",data.uid)
					userStore.setUserInfo({ uid: data.uid, ...data.userInfo });
					showToast("登录成功")
          router.navigateBack();
        },
        fail() {
					showToast("请检查网络")
        },
      });
    } catch (error: any) {
			showToast(error.message || "登录失败，请稍后重试")
      this.setData({ isLoading: false });
    }
  },
  /**
   * 触发协议区域的抖动动画
   */
  shakePrivacyArea() {
    this.setData({ shouldShake: true });
    setTimeout(() => {
      this.setData({ shouldShake: false });
    }, 500);
  },

  /**
   * 显示用户协议
   */
  showUserAgreement() {
    let url = encodeURIComponent("SquirrelRecycleUserAgreement.html");
    router.navigateTo("/pages/privacy/index", {
      query: {
        url,
      },
    });
  },

  /**
   * 显示隐私政策
   */
  showPrivacyPolicy() {
    let url = encodeURIComponent("SquirrelRecyclePrivacyPolicy.html");
    router.navigateTo("/pages/privacy/index", {
      query: {
        url,
      },
    });
  },
});
